package com.mrd.modules.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.alibaba.fastjson.JSONObject;
import com.mrd.base.utils.R;

/**
 * Created by Administrator on 2016/3/22.
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object map)
      throws Exception {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    httpServletResponse.sendRedirect("login");
    return false;
  }

  @Override
  protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
      ServletRequest request, ServletResponse response) throws Exception {
    // 删除上次链接
    Session session = subject.getSession();
    session.removeAttribute("shiroSavedRequest");
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))) {// 不是ajax请求
      issueSuccessRedirect(request, response);
    } else {
      httpServletResponse.setCharacterEncoding("UTF-8");
      PrintWriter out = httpServletResponse.getWriter();
      R r = R.ok();
      out.println(JSONObject.toJSONString(r));
      out.flush();
      out.close();
    }
    return false;
  }
}
